import { message } from "antd";
import { useEffect } from "react";
import { useSelector } from "react-redux";
import { matchRoutes, useLocation, useNavigate } from "react-router-dom";
import {rootRouter}  from "./index";

const AuthRoute = ({ children, auth }: any) => {
  const navigate = useNavigate();
  let location = useLocation()
  const token = useSelector((state: any) => state.global.token);
  const mathchs = matchRoutes(rootRouter, location);
  const isExist = mathchs?.some((item) => item.pathname == location.pathname);

  useEffect(() => {
    if (!token ) {
      // message.error("token 过期，请重新登录!");
      navigate("/login");
    }
    // 这里判断条件是：token 存在并且是匹配到路由并且是已经登录的状态
   else  if (token && isExist ) {
      // 如果你已经登录了，但是你通过浏览器里直接访问login的话不允许直接跳转到login路由，必须通过logout来控制退出登录或者是token过期返回登录界面
      if (location.pathname == "/" || location.pathname == "/login") {
        // message.error("已登录,请勿重复登录!")
        navigate("/home/schedule/free");
        // console.log(location.pathname);
      } else {
        // 如果是其他路由就跳到其他的路由
        // navigate(location.pathname);
        // console.log(location.pathname);
      }
    }
  }, [token, location.pathname]);

  return children;
};
export default AuthRoute;
